#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>

const static int g_sockfd = -1;

class TcpClient
{
public:
    TcpClient(std::string ip, uint16_t port)
        : _sockfd(g_sockfd), _ip(ip), _port(port)
    {
        // 1、创建sockfd
        _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "sockfd create error" << std::endl;
            exit(1);
        }
        // 2、绑定服务端的 ip 和 端口
        memset(&_server, 0, sizeof(_server));
        _server.sin_family = AF_INET;
        _server.sin_port = htons(_port);
        ::inet_pton(AF_INET, _ip.c_str(), &_server.sin_addr);
        // 3、建立链接
        int n = ::connect(_sockfd, (struct sockaddr*)&_server, sizeof(_server));
        if (n < 0)
        {
            std::cerr << "connect error" << std::endl;
            exit(2);
        }
    }

    void Start()
    {
        char buffer[1024];
        while (true)
        {
            std::cout << "Please Enter# ";
            std::string message;
            std::getline(std::cin, message);

            // 向服务器发送请求
            ssize_t n = ::write(_sockfd, message.c_str(), message.size());
            if (n < 0)
            {
                std::cerr << "write error" << std::endl;
                break;
            }
            // 接收响应
            n = ::read(_sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cerr << "read the end of file" << std::endl;
                break;
            }
            else
            {
                std::cerr << "read error" << std::endl;
                break;
            }
        }
    }

    ~TcpClient()
    {
        if (_sockfd > g_sockfd)
        {
            ::close(_sockfd);
        }
    }

private:
    int _sockfd;                // sockfd 文件描述符
    std::string _ip;            // 主机的 ip
    uint16_t _port;             // 主机端口
    struct sockaddr_in _server; // 服务端的信息结构体
};